<script setup lang="ts">
import { computed, ref } from "vue";
import { BigDecimal } from "@chulei-ui/utils";
import { storeToRefs } from "pinia";
import { sum } from "lodash-unified";
import { useMarketStore } from "../../src/cache/MarketStore";
import { NumberUtils } from "../../src/utils";
import UniverseTypeIcon from "../universe-type/UniverseTypeIcon.vue";
import type { ActivityMaterialItem } from "../../src/sde/entity";
import UniverseTypePrice from "~components/universe-type/UniverseTypePrice.vue";

const props = defineProps<{
  input?: ActivityMaterialItem[];
  output?: ActivityMaterialItem[];
  invention?: boolean;
}>();

const marketStore = useMarketStore();
const { typePrices } = storeToRefs(marketStore);

const leftDefaultChecked = computed(() => {
  return props.input?.map((item) => item.id);
});

const rightDefaultChecked = computed(() => {
  return props.output?.map((item) => item.id);
});

const data = computed(() => {
  return [props.input ?? [], props.output?.map((out) => ({ ...out, out: true })) ?? []]
    .flatMap((i) => i)
    .map((item) => {
      const price = typePrices.value.get(item.id);
      const quantity = getFinalQuantity(item);
      return {
        key: item.id,
        ...item,
        quantity,
        price: {
          buy_high: getItemPrice(price?.buy_high, quantity),
          sell_low: getItemPrice(price?.sell_low, quantity),
          estimate_price: getItemPrice(price?.estimate_price, quantity),
        },
      };
    });
});
const getItemTotalPrice = (items?: ActivityMaterialItem[]) => {
  return NumberUtils.readableText(
    sum(
      (
        items?.map((item) => {
          const price = typePrices.value.get(item.id);
          if (type.value === "buy") {
            return getItemPrice(price?.buy_high, getFinalQuantity(item));
          }
          if (type.value === "sell") {
            return getItemPrice(price?.sell_low, getFinalQuantity(item));
          }
          if (type.value === "estimate") {
            return getItemPrice(price?.estimate_price, getFinalQuantity(item));
          }
          return 0;
        }) as number[]
      ).filter((i) => i) ?? []
    )
  );
};

const totalInputPrice = computed(() => {
  return getItemTotalPrice(props.input);
});
const totalOutputPrice = computed(() => {
  return getItemTotalPrice(props.output?.map((out) => ({ ...out, out: true })));
});
const otherLoss = ref(0);

const blueprintLoss = ref(10);

const type = ref("buy");

const getItemPrice = (price?: number, quantity?: number) => {
  return BigDecimal.form(price)?.multiply(quantity)?.toFixed(2)?.toNumber();
};

const getFinalQuantity = (item: ActivityMaterialItem & { out?: boolean }) => {
  if (item.out || props.invention) return item.quantity;
  const number = BigDecimal.form(1)
    ?.subtract(BigDecimal.form(blueprintLoss.value)?.plus(otherLoss.value).divide(100))
    .multiply(item.quantity)
    .toFixed(2)
    ?.toNumber();
  if (number) {
    return Math.ceil(number);
  }
  return number;
};

const out = ref<number[]>(rightDefaultChecked.value ?? []);
</script>

<template>
  <el-card>
    <template #header>
      <el-space>
        <el-radio-group v-model="type">
          <el-radio value="buy">买单最高</el-radio>
          <el-radio value="sell">卖单最低</el-radio>
          <el-radio value="estimate">估价</el-radio>
        </el-radio-group>

        <div class="flex items-center">
          <el-input-number v-model="otherLoss" :min="0" :max="100" :controls="false" placeholder="请输入额外效率" />
          <el-tag type="info" style="height: 100%; margin-left: -6px">额外效率(%)</el-tag>
        </div>
        <div class="flex items-center">
          <el-input-number
            v-model="blueprintLoss"
            :min="0"
            :max="10"
            :controls="false"
            :precision="0"
            placeholder="请输入材料等级"
          />
          <el-tag type="info" style="height: 100%; margin-left: -6px">蓝图效率(%)</el-tag>
        </div>
      </el-space>
    </template>
    <el-transfer
      v-if="input && output"
      v-model="out"
      class="transfer"
      :data="data"
      :titles="[`输入(${totalInputPrice ?? '无'})`, `输出(${totalOutputPrice ?? '无'})`]"
      :left-default-checked="leftDefaultChecked"
      :right-default-checked="rightDefaultChecked"
    >
      <template #default="{ option }">
        <div class="flex items-center space-x-1">
          <UniverseTypeIcon :id="option.id" />
          <UniverseTypePrice :id="option.id" :show-price="false" />
          <el-tag type="info" size="small">
            <el-tooltip :content="`${option.quantity}`">
              {{ NumberUtils.readableText(option.quantity) }}
            </el-tooltip>
          </el-tag>
          <el-tag v-if="option.price?.buy_high && type === 'buy'" type="danger">
            {{ NumberUtils.readableText(option.price.buy_high) }}
          </el-tag>
          <el-tag v-if="option.price?.sell_low && type === 'sell'" type="danger">
            {{ NumberUtils.readableText(option.price.sell_low) }}
          </el-tag>
          <el-tag v-if="option.price?.estimate_price && type === 'estimate'" type="danger">
            {{ NumberUtils.readableText(option.price.estimate_price) }}
          </el-tag>
        </div>
      </template>
    </el-transfer>
  </el-card>
</template>

<style scoped lang="scss">
.transfer {
  --el-transfer-panel-width: 400px;
  ::v-deep(.el-checkbox__input) {
    display: none;
  }
  ::v-deep(.el-checkbox__label) {
    padding-left: unset !important;
  }
  ::v-deep(.el-button) {
    display: none;
  }
}
</style>
